﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Caching;
using System.Web.Mvc;
using StockMatch.Service;
using StockMatch.Service.Entity;
using Titan;

namespace StockMatch.WebSite.Controllers
{
    public class UserController : UserStockControllerBase
    {
        public ActionResult Index(int id)
        {
            ViewBag.Menu = "user";
            ViewBag.UserMenu = "UserIndex";
            User user =ServiceManager.UserService.GetUser(id);
            return View(user);
        }

        public ActionResult DayWin(int id)
        {
            ViewBag.UserMenu = "UserDayWin";

            QueryExpression query=new QueryExpression();
            query.EntityType = typeof (DayWinProject);
            query.Select(DayWinProject_.ProjectId);
            query.Select(DayWinProject_.ProjectNumber);
            query.Select(DayWinProject_.TotalTrade);
            query.Select(DayWinProject_.LossWarLine);
            query.Select(DayWinProject_.LossOpenLine);
            query.Select(DayWinProject_.ManageMoney);
            query.Select(DayWinProject_.ProjectState);
            query.Select(DayWinProject_.StartProjectTime);
            query.Select(DayWinProject_.TradingAccount);
            query.Select(DayWinProject_.TradingPassword);
            query.OrderBy(DayWinProject_.StartProjectTime.Desc);
            query.Where(DayWinProject_.UserId.TEqual(id));
            query.ReturnMatchedCount = true;
            DayWinProjects dayWinProjects= ServiceManager.DayWinProjectService.GetDayWinProjects(query);
            return View(dayWinProjects);
        }

        public ActionResult WeekWin(int id)
        {
            ViewBag.UserMenu = "UserWeekWin";
            QueryExpression query = new QueryExpression();
            query.EntityType = typeof(WeekWinProject);
            query.Select(WeekWinProject_.ProjectId);
            query.Select(WeekWinProject_.ProjectNumber);
            query.Select(WeekWinProject_.TotalTrade);
            query.Select(WeekWinProject_.LossWarLine);
            query.Select(WeekWinProject_.LossOpenLine);
            query.Select(WeekWinProject_.ManageMoney);
            query.Select(WeekWinProject_.ProjectState);
            query.Select(WeekWinProject_.StartProjectTime);
            query.Select(WeekWinProject_.TradingAccount);
            query.Select(WeekWinProject_.TradingPassword);
            query.OrderBy(WeekWinProject_.StartProjectTime.Desc);
            query.Where(WeekWinProject_.UserId.TEqual(id));
            query.ReturnMatchedCount = true;
            WeekWinProjects weekWinProjects = ServiceManager.WeekWinProjectService.GetWeekWinProjects(query);
            return View(weekWinProjects);
        }

        public ActionResult Stock(int id)
        {
            ViewBag.UserMenu = "UserStock";
            QueryExpression query = new QueryExpression();
            query.EntityType = typeof(Project);
            query.Select(Project_.ProjectId);
            query.Select(Project_.ProjectNumber);
            query.Select(Project_.TotalTrade);
            query.Select(Project_.LossWarLine);
            query.Select(Project_.LossOpenLine);
            query.Select(Project_.LoanMoon);
            query.Select(Project_.ProjectState);
            query.Select(Project_.StartProjectTime);
            query.Select(Project_.TradingAccount);
            query.Select(Project_.TradingPassword);
            query.OrderBy(Project_.StartProjectTime.Desc);
            query.Where(Project_.UserId.TEqual(id));
            query.ReturnMatchedCount = true;
            Projects projects = ServiceManager.ProjectService.GetProjects(query);
            return View(projects);
        }

        #region 个人信息
        
        [HttpGet]
        public ActionResult UserInfo(int id)
        {
            ViewBag.UserMenu = "UserInfo";

            //获取当前登录人信息
            var user = ServiceManager.UserService.GetUser(id);
            return View(user);
        }

        public ActionResult UserEdit(int id)
        {
            ViewBag.UserMenu = "UserInfo";
            //获取当前登录人信息
            var user = ServiceManager.UserService.GetUser(id);
            return View(user);
        }

        [HttpPost]
        public ActionResult UserEdit(User user)
        {
            ViewBag.UserMenu = "UserInfo";
            var updatePropetry = new PropertyExpression[]
                {
                    User_.Province,
                    User_.City,
                    User_.Address,
                    User_.IsMarriage,
                    User_.Education,
                    User_.Industry,
                    User_.Position,
                    User_.MonthlySalary
                };
            bool rs = ServiceManager.UserService.Update(user, updatePropetry);
            if (rs)
            {
                return Content("<script>alert('个人信息修改成功！');location.href='" + Url.Action("UserInfo", "User",new{id= user.UserId}) + "'</script>", "text/html");
            }
            return Content("<script>alert('个人信息修改失败！');location.href='" + Url.Action("UserEdit", "User",new{id= user.UserId}) + "'</script>", "text/html");
        }

        #endregion 个人信息

        public ActionResult Security(int id)
        {
            ViewBag.UserMenu = "Security";
            var user = ServiceManager.UserService.GetUser(id);
            return View(user);
        }

        #region 实名认证
        /// <summary>
        /// 实名认证
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="userTrueName"></param>
        /// <param name="userCard"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult CardAuthentication(int userId,string userTrueName,string userCard)
        {
            if (string.IsNullOrEmpty(userTrueName.Trim()))
            {
                return Json(new {code = 0, message = "真实姓名不能为空"});
            }
            if (string.IsNullOrEmpty(userCard.Trim()))
            {
                return Json(new { code = 0, message = "身份证号不能为空" });
            }
            if (!CommonFunc.CheckIDCard(userCard))
            {
                return Json(new { code = 0, message = "身份证号不合法" });
            }
            User user = new User
            {
                UserId = userId,
                UserTrueName = userTrueName,
                UserCard = userCard,
                NameAuthenticationState = 1
            };
            if (ServiceManager.UserService.Update(user, User_.UserCard, User_.UserTrueName,User_.NameAuthenticationState))
            {
                return Json(new { code = 1, message = "认证成功" });
            }
            return Json(new { code = 0, message = "认证失败" });
        }
        /// <summary>
        /// 上传照片
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UploadPhoto(int userId)
        {
            string[] extensions = new[] {".jpg", ".png", ".gif"};
            string[] strings =new string[3];
            if (Request.Files.Count > 0)
            {
                int i = 0;
                foreach (string key in Request.Files)
                {
                    var file = this.Request.Files[key];
                    if (file == null || file.ContentLength == 0)
                    {
                        continue;
                    }

                    string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                        string.Format("/{0}/{1}/", userId, WebConfig.UploadFilePath));
                    string extension = Path.GetExtension(file.FileName);
                    if (extensions.All(p => p != extension))
                    {
                        return Json(new { code = 0, message = "照片格式错误，必须是.jpg、.png、.gif" });
                    }
                    string fileName = Guid.NewGuid() + extension;
                    if (!Directory.Exists(filePath))
                    {
                        Directory.CreateDirectory(filePath);
                    }
                    filePath = Path.Combine(filePath, fileName);

                    file.SaveAs(filePath);
                    strings[i] = fileName;
                    i++;
                }
            }
            return UserPhotos(userId, strings[0], strings[1], strings[2]);
        }
        /// <summary>
        /// 提交照片到数据库
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="userCardPhoto1"></param>
        /// <param name="userCardPhoto2"></param>
        /// <param name="userCardPhoto3"></param>
        /// <returns></returns>
        private ActionResult UserPhotos(int userId, string userCardPhoto1, string userCardPhoto2, string userCardPhoto3)
        {
            if (string.IsNullOrEmpty(userCardPhoto1))
            {
                return Json(new {code = 0, message = "身份证正面照片必须上传"});
            }
            if (string.IsNullOrEmpty(userCardPhoto2))
            {
                return Json(new {code = 0, message = "身份证背面照片必须上传"});
            }
            if (string.IsNullOrEmpty(userCardPhoto3))
            {
                return Json(new {code = 0, message = "手持身份证照片必须上传"});
            }
            User user = new User
            {
                UserId = userId,
                UserCardPhoto1 = userCardPhoto1,
                UserCardPhoto2 = userCardPhoto2,
                UserCardPhoto3 = userCardPhoto3,
                NameAuthenticationState = 3
            };
            if (ServiceManager.UserService.Update(user, User_.UserCardPhoto1, User_.UserCardPhoto2, User_.UserCardPhoto3,User_.NameAuthenticationState))
            {
                return Json(new {code = 1, message = "上传照片成功"});
            }
            return Json(new {code = 0, message = "上传照片失败"});
        }

        #endregion

        #region 绑定手机

        /// <summary>
        /// 绑定新手机
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="phome"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UpdatePhone(int userId, string phome,string code)
        {
            if (string.IsNullOrEmpty(phome))
            {
                return Json(new { code = 0, message = "手机号不能为空" });
            }
            phome = phome.Trim();
            string pattern = @"^(\({0,1}\d{3,4})\){0,1}(-){0,1}(\d{7,8})$";
            if (!Regex.IsMatch(phome, pattern, RegexOptions.Compiled))
            {
                return Json(new { code = 0, message = "手机号格式错误" });
            }
            string validateCode = Request.GetCookieValue("MessageValidateCode");
            if (validateCode == null)
            {
                return Json(new { code = 0, message = "请重新获取短信验证码" });
            }
            if (code.ToLower()!= validateCode.ToLower())
            {
                return Json(new { code = 0, message = "取短信验证码错误" });
            }

            User user = new User
            {
                UserId = userId,
                Phone = phome
            };
            if (ServiceManager.UserService.Update(user, User_.Phone))
            {
                return Json(new { code = 1, message = "修改手机号成功" });
            }
            return Json(new { code = 0, message = "修改手机号失败" });
        }
        /// <summary>
        /// 发送手机短信验证码
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SendLockCode(string phone)
        {
            Response.SetCookie("MessageValidateCode", CommonFunc.SendLockCode(phone));
            return Json(new { code = 1 });
        }
        /// <summary>
        /// 验证发生的短信验证码
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult CheckSendLockCode(string code)
        {
            string validateCode = Request.GetCookieValue("MessageValidateCode");
            int ret = 0;
            if (validateCode != null && code.ToLower() == validateCode.ToLower())
            {
                ret = 1;
            }
            return Json(new {data = ret});
        }
        /// <summary>
        /// 图片验证码
        /// </summary>
        /// <returns></returns>
        public ActionResult ValidateCode()
        {
            ValidateCode validateCode = new ValidateCode();
            validateCode.Width = 100;
            validateCode.Height = 35;
            //生成验证码指定的长度
            string code = validateCode.GetRandomString(4);
            Response.SetCookie("RegistValidateCode", code);
            //创建验证码的图片
            byte[] bytes = validateCode.CreateImage(code);
            //最后将验证码返回
            return File(bytes, @"image/jpeg");
        }
        /// <summary>
        /// 验证图片验证码
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult CheckValidateCode(string code)
        {
            string validateCode = Request.GetCookieValue("RegistValidateCode");
            int ret = 0;
            if (code.ToLower() == validateCode.ToLower())
            {
                ret = 1;
            }
            return Json(new { data = ret });
        }
        #endregion

        #region 绑定邮箱
        public ActionResult SendEmail(string email)
        {
            Response.SetCookie("EmailValidateCode", CommonFunc.SendEmail(email));
            return Json(new { code = 1 });
        }

        public ActionResult CheckEmailValidateCode(string code)
        {
            string validateCode = Request.GetCookieValue("EmailValidateCode");
            if (validateCode == null || code.ToLower() != validateCode.ToLower())
            {
                return Json(new {code = 0, message = "验证码错误，请重新发送"});
            }
            return Json(new { code = 1, message = "ok" });
        }

        public ActionResult BindEmail(int id, string email,string code)
        {
            if (string.IsNullOrEmpty(email))
            {
                return Json(new { code = 0, message = "邮箱不能为空" });
            }
            if (string.IsNullOrEmpty(code))
            {
                return Json(new { code = 0, message = "验证码不能为空" });
            }
            string validateCode = Request.GetCookieValue("EmailValidateCode");
            if (validateCode == null || code.ToLower() != validateCode.ToLower())
            {
                return Json(new { code = 0, message = "验证码错误，请重新发送" });
            }
            User user = new User
            {
                UserId = id,
                Email = email
            };
            if (ServiceManager.UserService.Update(user, User_.Email))
            {
                return Json(new { code = 1, message = "邮箱绑定成功" });
            }
            return Json(new { code = 0, message = "邮箱绑定失败" });
        }
        #endregion

        #region 修改登录密码

        public ActionResult UpdateLoaginPassword(int userId,string oldPassword,string newPassword1,string newPassword2)
        {
            if (string.IsNullOrEmpty(oldPassword))
            {
                return Json(new { code = 0, message = "原登录密码不能为空" });
            }
            if (string.IsNullOrEmpty(newPassword1))
            {
                return Json(new { code = 0, message = "新登录密码不能为空" });
            }
            if (!Regex.IsMatch(newPassword1, @"^[0-9|a-z|A-Z]{6,}$"))
            {
                return Json(new { code = 0, message = "登录密码格式错误" });
            }
            if (oldPassword == newPassword1)
            {
                return Json(new { code = 0, message = "新密码不能跟原始密码相同" });
            }
            if (string.IsNullOrEmpty(newPassword2))
            {
                return Json(new { code = 0, message = "确认新登录密码不能为空" });
            }
            if (newPassword2!=newPassword1)
            {
                return Json(new { code = 0, message = "两次输入的密码不一致" });
            }
            User user = ServiceManager.UserService.GetUser(userId);
            if (user == null)
            {
                return Json(new { code = 0, message = "该用户不存在" });
            }
            if (user.UserPassword !=Encryption.GetMD5HashHex(oldPassword))
            {
                return Json(new { code = 0, message = "原登录密码错误" });
            }
            user = new User
            {
                UserId = userId,
                UserPassword = Encryption.GetMD5HashHex(newPassword1)
            };
            if (ServiceManager.UserService.Update(user,User_.UserPassword))
            {
                return Json(new { code = 1, message = "ok" });
            }
            return Json(new { code = 0, message = "修改登录密码失败" });
        }

        #endregion

        #region 设置提现密码
        public ActionResult SetDrawingPassword(int userId, string password1, string password2)
        {
            if (string.IsNullOrEmpty(password1))
            {
                return Json(new { code = 0, message = "提现密码不能为空" });
            }
            if (string.IsNullOrEmpty(password2))
            {
                return Json(new { code = 0, message = "确认提现密码不能为空" });
            }
            if (password2 != password1)
            {
                return Json(new { code = 0, message = "两次输入的密码不一致" });
            }
            User user = ServiceManager.UserService.GetUser(userId);
            if (user == null)
            {
                return Json(new { code = 0, message = "该用户不存在" });
            }
            
            user = new User
            {
                UserId = userId,
                DrawingPassword = Encryption.GetMD5HashHex(password1)
            };
            if (ServiceManager.UserService.Update(user, User_.DrawingPassword))
            {
                return Json(new { code = 1, message = "ok" });
            }
            return Json(new { code = 0, message = "设置提现密码失败" });
        }
        public ActionResult UpdateDrawingPassword(int userId,string oldPassword, string password1, string password2)
        {
            if (string.IsNullOrEmpty(oldPassword))
            {
                return Json(new { code = 0, message = "原提现密码不能为空" });
            }
            if (string.IsNullOrEmpty(password1))
            {
                return Json(new { code = 0, message = "提现密码不能为空" });
            }
            if (string.IsNullOrEmpty(password2))
            {
                return Json(new { code = 0, message = "确认提现密码不能为空" });
            }
            if (password2 != password1)
            {
                return Json(new { code = 0, message = "两次输入的密码不一致" });
            }
            if (oldPassword == password1)
            {
                return Json(new { code = 0, message = "新密码不能跟原始密码相同" });
            }

            User user = ServiceManager.UserService.GetUser(userId);
            if (user == null)
            {
                return Json(new { code = 0, message = "该用户不存在" });
            }
            if (user.DrawingPassword != Encryption.GetMD5HashHex(oldPassword))
            {
                return Json(new { code = 0, message = "原体现密码错误" });
            }
            user = new User
            {
                UserId = userId,
                DrawingPassword = Encryption.GetMD5HashHex(password1)
            };
            if (ServiceManager.UserService.Update(user, User_.DrawingPassword))
            {
                return Json(new { code = 1, message = "ok" });
            }
            return Json(new { code = 0, message = "修改提现密码失败" });
        }
        #endregion

        public ActionResult Messager(int id)
        {
            ViewBag.UserMenu = "Messager";
            return View();
        }

        [HttpPost]
        public ActionResult PostMessager(int messageTypeId, string messageInfo)
        {
            if (messageTypeId==0)
            {
                return Json(CommonFunc.Result(0, "请选择留言类型"));
            }
            if (string.IsNullOrEmpty(messageInfo))
            {
                return Json(CommonFunc.Result(0, "留言内容不能为空"));
            }
            if (CurrentUser == null)
            {
                return Json(CommonFunc.Result(0, "请先登录"));
            }
            OnlineMessage onlineMessage=new OnlineMessage();
            onlineMessage.MessageTypeId = messageTypeId;
            onlineMessage.MessageInfo = messageInfo;
            onlineMessage.UserId = CurrentUser.UserId;
            if (ServiceManager.OnlineMessageService.Insert(onlineMessage))
            {
                return Json(CommonFunc.Result(1, "ok"));
            }
            return Json(CommonFunc.Result(0, "留言失败"));
        }


    }
}